import router from "@/router";
import {userStore} from "@/store/user";
import {menuStore} from "@/store/menu";

//白名单
const whiteList = ['/login']

router.beforeEach(async (to, from, next)=>{
    const usStore = userStore()
    const mstore = menuStore()
    //获取token
    const token = usStore.getToken
    if(token){
        //判断是否登录或者首页
        if(to.path=='/login' || to.path==='/'){
            //如果是登录或者首页，直接去首页
            next({path:'/'})
        }else{
            //判断权限是否存在
            const hasRoles = usStore.getCodeLIst.length>0
            if(hasRoles){
                next()
            }else{
                try {
                    //如果不存在权限，就从后天获取
                    await usStore.getInfo()
                    await mstore.getMenuList(router,usStore.getUserId)
                    //等待路由完全加载
                    next({...to,replace:true})
                }catch(err){
                    localStorage.clear()
                    next({path:'/login'})
                }

            }
        }
    }else{
        console.log(whiteList.indexOf(to.path))
        if(whiteList.indexOf(to.path) !== -1){
            next() //在白名单里面，放行
        }else{
            //不在白名单且没有token，跳转登录
            next({path:'/login'})
        }
    }
})